package by.gravity.pvh.data;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.os.AsyncTask;
import by.gravity.pvh.http.HttpClient;

public class RateDataManager {
	private static RateDataManager instance;

	private static final String BASE_URL = "http://query.yahooapis.com/v1/public/yql?q=%s&env=store://datatables.org/alltableswithkeys&format=json&unused=%d";

	private static final String QUERY_URL = "select * from yahoo.finance.xchange where pair in (\"USDBYR\")";

	private static final String QUERY = "query";

	private static final String RESULTS = "results";

	private static final String RATE = "rate";

	private static final String RATE_VALUE = "Rate";

	private static final String ID = "id";

	public static RateDataManager getInstance() {
		if (instance == null) {
			instance = new RateDataManager();
		}

		return instance;
	}

	private RateDataManager() {

	}

	private String getUrl() {

		try {
			return String.format(BASE_URL, URLEncoder.encode(QUERY_URL, "UTF-8"), System.currentTimeMillis());
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return null;
	}

	private String getRate(String responce) {

		try {
			JSONObject jsonObject = new JSONObject(responce);
			if (jsonObject.has(QUERY)) {
				JSONObject query = jsonObject.getJSONObject(QUERY);
				if (query.has(RESULTS)) {
					JSONObject result = query.getJSONObject(RESULTS);
					if (result.has(RATE)) {
						JSONObject rate = result.getJSONObject(RATE);
						if (rate.getString(ID).length() == 6) {
							if (rate.has(RATE_VALUE)) {
								return String.valueOf(rate.getDouble(RATE_VALUE));
							}
						}
					}
				}
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}

		return null;
	}

	public interface onLoadCompleteListener {
		public void onLoadComplete(String result);
	}

	public void getRate(final Context context, final onLoadCompleteListener listener) {
		new AsyncTask<Void, Void, String>() {

			@Override
			protected String doInBackground(Void... params) {
				HttpClient client = HttpClient.get(context);
				try {
					String responce = client.loadAsString(getUrl());
					String rate = getRate(responce);
					return rate;
				} catch (IOException e) {
					e.printStackTrace();
				}

				return null;
			}

			@Override
			protected void onPostExecute(String result) {
				super.onPostExecute(result);
				if (result != null) {
					listener.onLoadComplete(result);
				}
			}

		}.execute();
	}
}
